package formework.aop;

import formework.aop.intercept.DemoMethodInvocation;
import formework.aop.support.DemoAdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class DemoJdkDynamicAopProxy implements DemoAopProxy , InvocationHandler {


    private DemoAdvisedSupport advised;

    public DemoJdkDynamicAopProxy(DemoAdvisedSupport config){
        this.advised = config;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        List<Object> interceptorsAndDynamicMethodMatchers = advised.getInterceptorsAndDynamicInterceptionAdvice(method, advised.getTargetClass());

        DemoMethodInvocation invocation = new DemoMethodInvocation(proxy, advised.getTarget(), method, args,advised.getTargetClass(), interceptorsAndDynamicMethodMatchers);
        return invocation.proceed();
    }

    @Override
    public Object getProxy() {
        return getProxy(advised.getClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader,advised.getTargetClass().getInterfaces(),this);
    }
}
